package com.lottery.material.controller.portal.article;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.pojo.article.ArticleInfo;
import com.lottery.material.pojo.portaluser.CommentInfo;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.user.CommentInfoService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.*;
import com.lottery.material.vo.portal.comment.ArticleCommentVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description:    文章评论Controller
 * Author:         sunny
 * CreateDate:     2019-04-25 10:17
 */
@RequestMapping("/portal/article")
@Slf4j
@Controller
public class ArticleCommentController extends BaseController {

    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @Autowired
    private CommentInfoService commentInfoService;
    @Autowired
    private ArticleInfoService articleInfoService;
    @Autowired
    private PortalUserInfoService portalUserInfoService;


    /**
     * description: 获取文章评论列表
     * author sunny
     * createDate 2019-04-25 上午 10:19
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCommentPageList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getCommentPageList(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }
        String isViewLord = reqParamMap.get("isViewLord");
        if (StringUtils.isBlank(isViewLord)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "isViewLord");
        } else if (!"1".equals(isViewLord) && !"2".equals(isViewLord)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "isViewLord");
        }

        String sortType = reqParamMap.get("sortType");
        if (StringUtils.isBlank(sortType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "sortType");
        } else if (!"asc".equals(sortType) && !"desc".equals(sortType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "sortType");
        }

        String page = reqParamMap.get("page");
        String refreshTime = reqParamMap.get("refreshTime");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "page");
        } else {
            if ("1".equals(page)) {
                refreshTime = CalendarUtil.getNowDate();
            } else {
                if (StringUtils.isBlank(refreshTime)) {
                    return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "refreshTime");
                }
            }
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            //封装响应数据
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("refreshTime", refreshTime);

            String userId = reqParamMap.get("userId");
            String accessToken = reqParamMap.get("accessToken");
            if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(accessToken)) {
                Object hget = jedisClient.hget("portalUser", userId);
                String s = String.valueOf(hget);
                if (!accessToken.equals(s)) {
                    return ResponseResult.buildResult(ResultEnum.LOGIN_OUTOFDATE_ERROR);
                }

                if (userId.equals(articleInfo.getUserId())) { //作者本人
                    responseMap.put("isAuthor", "2");
                } else {
                    responseMap.put("isAuthor", "1");
                }
            } else {
                responseMap.put("isAuthor", "1");
            }

            Map<String, Object> commentMap = new HashMap<String, Object>();
            commentMap.put("refreshTime", refreshTime);
            commentMap.put("articleId", articleId);
            commentMap.put("isViewLord", isViewLord);
            commentMap.put("sortType", sortType);
            commentMap.put("pageIndex", Const.PORTAL_PAGE * (Integer.valueOf(page) - 1));
            commentMap.put("pageCount", Const.PORTAL_PAGE);
            List<ArticleCommentVo> articleCommentVos = commentInfoService.findCommentPageList(commentMap);

            responseMap.put("comment", articleCommentVos);
            return ResponseResult.buildResult(ResultEnum.SUCCESS, responseMap);
        } catch (Exception e) {
            log.error("【获取文章评论分页列表出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_COMMENT_PAGE_LIST_EXCEPTION);
        }
    }

    /**
     * description: 文章评论
     * author sunny
     * createDate 2019-04-25 下午 7:53
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/goComment", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult goComment(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String articleId = reqParamMap.get("articleId");
        if (StringUtils.isBlank(articleId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "articleId");
        }
        String commentContent = reqParamMap.get("commentContent");
        if (StringUtils.isBlank(commentContent)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "commentContent");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            ArticleInfo articleInfo = articleInfoService.findByArticleId(articleId);
            if (Objects.isNull(articleInfo)) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_NOT_EXIST_FAIL);
            }

            //封装数据
            String userId = reqParamMap.get("userId");
            CommentInfo commentInfo = new CommentInfo();
            if (userId.equals(articleInfo.getUserId())) {
                commentInfo.setIsLord(2);
            } else {
                commentInfo.setIsLord(1);
            }

            String beCommentId = reqParamMap.get("beCommentId");
            if(StringUtils.isNotBlank(beCommentId)){
                CommentInfo beCommentInfo = commentInfoService.findByCommentId(beCommentId);
                commentInfo.setBeCommentId(beCommentInfo.getId());
                commentInfo.setBeFloor(beCommentInfo.getFloor());
                commentInfo.setBeUserId(beCommentInfo.getUserId());
                commentInfo.setBeCommentContent(beCommentInfo.getCommentContent());
            }

            commentInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
            commentInfo.setUserId(userId);
            commentInfo.setArticleId(articleId);
            commentInfo.setLikeTotal(0);
            commentInfo.setCommentContent(commentContent);

            //保存评论
            Integer flag = commentInfoService.saveCommentInfo(commentInfo);
            if (-1 == flag) {
                return ResponseResult.buildResult(ResultEnum.ARTICLE_COMMENT_FAIL);
            }
            return ResponseResult.buildResult(ResultEnum.ARTICLE_COMMENT_SUCCESS);
        } catch (Exception e) {
            log.error("【文章评论出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GO_COMMENT_EXCEPTION);
        }
    }
}
